package com.yellowcon.webssh.local;

import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletResponse;


import com.yellowcong.shiro.utils.ControllerUtils;

public class LocalTermClient {
	
	//用户的回复
	private HttpServletResponse  response;
	
		
	/**
	 * 获取本地
	 * @param session
	 */
	public LocalTermClient(HttpServletResponse response) {
		super();
		this.response = response;
	}
	
	/**
	 * 执行命令
	 * @param commandStr
	 */
	public void exeCmd(String commandStr) {
		try {
			//执行命令
			Process p = Runtime.getRuntime().exec(commandStr);
			
			//获取输出流
			InputStream in = p.getInputStream();
			
			//写数据到客户端
			writeToWeb(in);
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
	
	
	/**
	 * 写数据到web控制界面
	 * @param in
	 */
	private void writeToWeb(InputStream in) {
		
		CmdResult result = new CmdResult();
		try {
			//定义一个缓存
			//一个UDP 的用户数据报的数据字段长度为8192字节
			byte [] buff = new byte[8192];	
			
			int len =0;
			StringBuffer sb = new StringBuffer();
			while((len = in.read(buff)) > 0) {
				//读取数组里面的数据，进行补码
				for (int i = 0; i < len; i++){
					//进行补码操作
					char c = (char) (buff[i] & 0xff);
					sb.append(c);
				}
			}
			result.setError(false);
			result.setResult(new String(sb.toString().getBytes("ISO-8859-1"),"UTF-8"));
			//写数据到服务器端
			ControllerUtils.writeJSON(response, result);
		} catch (IOException e) {
			e.printStackTrace();
			result.setError(true);
			result.setResult(e.getMessage());
			//写数据到服务器端
			ControllerUtils.writeJSON(response, result);
		}
	}
	//执行结果
	static class CmdResult{
		//是否错误
		private boolean error;
		//返回的结果
		private String result;
		//返回的错误消息
		private String message; 
		
		public String getMessage() {
			return message;
		}
		public void setMessage(String message) {
			this.message = message;
		}
		public boolean isError() {
			return error;
		}
		public void setError(boolean error) {
			this.error = error;
		}
		public String getResult() {
			return result;
		}
		public void setResult(String result) {
			this.result = result;
		}
	}
}